﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Telerik.WinControls;
using Telerik.WinControls.UI;
using Aspose.Cells;
using System.IO;

namespace UnigenReport.Form
{
    public partial class ucInvoice : UserControl
    {
        private UnigenDataContext db;

        #region Thiết lập

        public ucInvoice()
        {
            InitializeComponent();
            //Phân quyền
            if (Variables.UserRoleID == 0)
                btnDelete.Visibility = ElementVisibility.Collapsed;
            if (Variables.UserRoleID != 4)
                btnApprove.Visibility = ElementVisibility.Collapsed;

            SetEvent();
            Common.SetMenuShortcut(btnInsert, btnUpdate, btnDelete, btnGetData, btnCloseForm);
            cboApprove.SelectedIndex = 1;
            cboListSize.SelectedIndex = 1;
            txtFromDate.Value = txtToDate.Value = DateTime.Now;
        }

        /// <summary>
        /// Khai báo các sự kiện
        /// </summary>
        private void SetEvent()
        {
            this.Load += OnLoad;
            this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
            this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            this.btnGetData.Click += new System.EventHandler(this.btnGetData_Click);            
            this.btnExportList.Click += btnExportList_Click;
            this.btnExportProduct.Click += btnExportProduct_Click;
            this.btnExport.Click += btnExport_Click;
            this.btnPrint.Click += btnPrint_Click;
            this.btnApprove.Click += new System.EventHandler(this.btnApprove_Click);
            this.btnCloseForm.Click += new System.EventHandler(this.btnCloseForm_Click);
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            this.chkFromDate.ToggleStateChanged += new StateChangedEventHandler(chkFromDate_ToggleStateChanged);
            this.chkToDate.ToggleStateChanged += new StateChangedEventHandler(chkToDate_ToggleStateChanged);
            this.grvInvoice.CellDoubleClick += new Telerik.WinControls.UI.GridViewCellEventHandler(this.grvInvoice_CellDoubleClick);        
        }

        /// <summary>
        /// Hàm load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoad(object sender, EventArgs e)
        {
            //Load default
            SetDefault();
        }

        /// <summary>
        /// Thiết lập các giá trị mặc định của form
        /// </summary>
        private void SetDefault()
        {
            //Bind dữ liệu chính
            BindData();
        }

        /// <summary>
        /// Lấy dữ liệu chính
        /// </summary>
        private void BindData()
        {
            try
            {
                //Data bind
                var size = Convert.ToInt32(cboListSize.Text);

                sourceInvoice.DataSource = GetData(size);

                //STT
                Common.SetNo(grvInvoice);
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("BindData - " + ex.Message);
            }
        }

        private List<Invoice> GetData(int size = 65000)
        {
            db = new UnigenDataContext();
            var sizeCondition = String.Empty;
            if (cboListSize.SelectedIndex > 0)
                sizeCondition += " TOP " + size;
            var whereCondition = " i.Active = 1";
            var inv = txtNo.Text.Trim();

            if (chkFromDate.Checked)
                whereCondition += " AND i.Date >= '" + txtFromDate.Value.ToString("yyyy/MM/dd 00:00") + "'";
            if (chkToDate.Checked)
                whereCondition += " AND i.Date <= '" + txtToDate.Value.ToString("yyyy/MM/dd 23:59") + "'";

            if (!String.IsNullOrEmpty(inv))
            {
                var noCondition = new List<string>();
                foreach (var str in inv.Split(','))
                    noCondition.Add(" i.InvoiceNo LIKE N'%" + str + "%'");

                whereCondition += " AND (" + String.Join(" OR", noCondition) + ")";
            }
            if (cboApprove.SelectedIndex == 1)
                whereCondition += " AND ISNULL(i.Approve,0) = 0";
            else if (cboApprove.SelectedIndex == 2)
                whereCondition += " AND ISNULL(i.Approve,0) = 1";

            return db.ExecuteQuery<Invoice>(String.Format("SELECT {0} * FROM Invoice i WHERE {1} ORDER BY i.InvoiceNo DESC"
                , sizeCondition, whereCondition)).ToList();
        }

        private List<ExportInvoiceProduct> GetDataForExportProducts()
        {
            db = new UnigenDataContext();
            var whereCondition = " i.Active = 1";
            var inv = txtNo.Text.Trim();

            if (!String.IsNullOrEmpty(inv))
            {
                var noCondition = new List<string>();
                foreach (var str in inv.Split(','))
                    noCondition.Add(" i.InvoiceNo LIKE N'%" + str + "%'");

                whereCondition += " AND (" + String.Join(" OR", noCondition) + ")";
            }
            if (cboApprove.SelectedIndex == 1)
                whereCondition += " AND ISNULL(i.Approve,0) = 0";
            else if (cboApprove.SelectedIndex == 2)
                whereCondition += " AND ISNULL(i.Approve,0) = 1";

            return db.ExecuteQuery<ExportInvoiceProduct>(String.Format(@"SELECT
                                                            id.ProductCode,
                                                            id.ProductName,
                                                            i.InvoiceNo,
                                                            id.WO,
                                                            id.Quantity,
                                                            id.Price,
                                                            id.Amount
                                                            FROM InvoiceDetail id
                                                            JOIN Invoice i ON i.InvoiceId = id.InvoiceId WHERE {0} ORDER BY i.InvoiceNo, id.ProductCode DESC"
                , whereCondition)).ToList();
        }

        #endregion

        #region Hàm

        private void Insert()
        {
            try
            {
                var newItem = new Form.ucInvoiceEdit() { Dock = DockStyle.Fill };
                var ui = Common.CreateForm(newItem, String.Empty, 1050, 690);
                ui.FormClosing += new FormClosingEventHandler(ui_FormClosing);
                if (ui.ShowDialog() == DialogResult.OK)
                {
                    BindData();
                    Common.ShowSaveSuccess();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Insert - " + ex.Message);
            }
        }

        private void ui_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(!((sender as RadForm).Controls[0] as ucInvoiceEdit).modifySaved)
                if(Common.ShowQuestion("Dữ liệu chưa lưu, bạn chắc chắn đóng không?") == DialogResult.Cancel)
                    e.Cancel = true;
        }

        private void UpdateInfo()
        {
            try
            {
                if (sourceInvoice.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                db = new UnigenDataContext();
                var selectedInv = sourceInvoice.Current as Invoice;
                var newestInv = db.Invoices.SingleOrDefault(p => p.InvoiceId == selectedInv.InvoiceId);

                var itemEdit = new Form.ucInvoiceEdit() { Dock = DockStyle.Fill }.ForUpdate(newestInv);
                var ui = Common.CreateForm(itemEdit, String.Empty, 1050, 690);

                if (ui.ShowDialog() == DialogResult.OK)
                {
                    BindData();
                    Common.ShowSaveSuccess();
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Update - " + ex.Message);
            }
        }

        private void Delete()
        {
            try
            {
                if (sourceInvoice.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                db = new UnigenDataContext();
                var inputItem = (sourceInvoice.Current as Invoice);
                if (inputItem.Approve ?? false)
                {
                    Common.ShowNoticeMess("Không thể xóa invoice đã xác nhận!");
                    return;
                }

                if (Common.ShowQuestion("Xóa invoice " + inputItem.InvoiceNo + " ?") != DialogResult.OK)
                    return;
                //Xóa
                var removeItem = db.Invoices.SingleOrDefault(p => p.InvoiceId == inputItem.InvoiceId);
                //removeItem.InvoiceNo += "_Deleted";
                //removeItem.Active = false;
                db.Invoices.DeleteOnSubmit(removeItem);

                //Thay đổi Ship request
                var requestIds = removeItem.RequestIds.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                foreach (var id in requestIds)
                {
                    var request = db.ShippingRequests.SingleOrDefault(p => p.RequestId == Convert.ToInt32(id));
                    if (request != null)
                        request.Status = 0;
                }

                db.SubmitChanges();

                //Remove khỏi grid
                sourceInvoice.Remove(inputItem);
                Common.SetNo(grvInvoice);

                //Thông báo
                Common.ShowSaveSuccess();
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Delete - " + ex.Message);
            }
        }

        /// <summary>
        /// Hàm kết xuất file
        /// </summary>
        /// <param name="fileName">Tên file, đường dẫn</param>
        /// <param name="exportType">Kiểu 0: Xuất, 1: In ngay</param>
        private void ExportFile(Invoice invoice, string fileName, int exportType)
        {
            try
            {
                //datacontext
                db = new UnigenDataContext();

                //Tạo một đối tượng workbook
                var stream = new MemoryStream(global::UnigenReport.Properties.Resources.InvoiceReport);
                var workbook = new Workbook(stream);
                var invoiceDetail = db.InvoiceDetails.Where(p => p.InvoiceId == invoice.InvoiceId).ToList();
                var invoicePL = db.InvoicePackingLists.Where(p => p.InvoiceId == invoice.InvoiceId).ToList();
                
                //XML variables
                var company = new SystemConfig.Company();
                var manufacturing = new SystemConfig.Manufacturing();
                var config = new SystemConfig.UserConfig();

                #region Sheet Invoice
                var wsInvoice = workbook.Worksheets[0];
                var cells = wsInvoice.Cells;
                //Default
                if (exportType == 1)
                    cells.Columns[13].IsHidden = true;

                cells["F1"].PutValue(company.Name);
                cells["F2"].PutValue(company.Address);
                cells["F3"].PutValue(company.Province);
                cells["F4"].PutValue("Tel: " + company.Phone);
                cells["H4"].PutValue("Fax: " + company.Fax);
                cells["C7"].PutValue(invoice.InvoiceNo);
                cells["B8"].PutValue(DateTime.Now);
                //Bill To
                cells["A10"].PutValue(invoice.BillToName);
                cells["A11"].PutValue(invoice.BillToAddress);
                cells["A12"].PutValue("Tel: " + invoice.BillToPhone);
                cells["A13"].PutValue("Fax: " + invoice.BillToFax);
                //Ship To
                cells["J10"].PutValue(invoice.ShipToName);
                cells["J11"].PutValue(invoice.ShipToAddress);
                cells["J12"].PutValue("Tel: " + invoice.ShipToPhone);
                cells["J13"].PutValue("Fax: " + invoice.ShipToFax);
                //Provider
                cells["C15"].PutValue(invoice.ShipVia);
                cells["C16"].PutValue(invoice.ShipTerm);
                cells["J15"].PutValue(invoice.ShippingAccount + ": ");
                cells["L15"].PutValue(invoice.ShippingAccountValue);
                cells["L16"].PutValue(invoice.Tracking);
                cells["O17"].PutValue(invoice.Currency);
                //bottom
                cells["E23"].PutValue(manufacturing.Name);
                cells["E24"].PutValue(manufacturing.Address);
                cells["E26"].PutValue(manufacturing.Country);
                cells["C32"].PutValue(config.PaymentTerm);

                //Summary
                cells["J30"].PutValue(invoiceDetail.Sum(p=>p.Quantity));
                cells["N30"].PutValue(invoiceDetail.Sum(p => p.Amount));
                cells["O30"].PutValue(invoiceDetail.Sum(p => p.ExportAmount));

                var rowIndex = 21;
                var itemCount = invoiceDetail.Count;
                //Chèn thêm n dòng vào dòng được chỉ định
                if (itemCount > 1)
                {
                    for (int i = 0; i < itemCount - 1; i++)
                    {
                        cells.InsertRow(rowIndex + i);
                        cells.CopyRow(cells, rowIndex - 1, (rowIndex + i));
                    }
                }

                //Bắt đầu đổ dữ liệu
                for (var i = 0; i < invoiceDetail.Count; i++)
                {
                    var item = invoiceDetail[i];

                    //Cột STT
                    cells["A" + rowIndex].PutValue(i + 1);
                    //PO
                    cells["B" + rowIndex].PutValue(item.PO);
                    //WO
                    cells["C" + rowIndex].PutValue(item.WO);
                    //Code
                    cells["D" + rowIndex].PutValue(item.ProductCode);
                    //Name
                    cells["E" + rowIndex].PutValue(item.ProductName);
                    //unit
                    cells["I" + rowIndex].PutValue(item.Unit);
                    //Quantity
                    cells["J" + rowIndex].PutValue(item.Quantity);
                    //Material Price
                    cells["K" + rowIndex].PutValue(item.MaterialPrice);
                    //Price
                    cells["L" + rowIndex].PutValue(item.Price);
                    //Export Price
                    cells["M" + rowIndex].PutValue(item.ExportPrice);
                    //Amount
                    cells["N" + rowIndex].PutValue(item.Amount);
                    //Export Amount
                    cells["O" + rowIndex].PutValue(item.ExportAmount);
                    //UhanCode
                    cells["Q" + rowIndex].PutValue(item.UhanCodeUsing);

                    rowIndex++;
                }
                #endregion

                #region Sheet Packing list
                var wsPackingList = workbook.Worksheets[1];
                cells = wsPackingList.Cells;
                //Default
                if (invoice.PackingType == 0)
                    cells.Columns[10].IsHidden = true;
                cells["F1"].PutValue(company.Name);
                cells["F2"].PutValue(company.Address);
                cells["F3"].PutValue(company.Province);
                cells["F4"].PutValue("Tel: " + company.Phone);
                cells["I4"].PutValue("Fax: " + company.Fax);
                cells["C7"].PutValue(invoice.InvoiceNo);
                cells["B8"].PutValue(DateTime.Now);
                //Bill To
                cells["A10"].PutValue(invoice.BillToName);
                cells["A11"].PutValue(invoice.BillToAddress);
                cells["A12"].PutValue("Tel: " + invoice.BillToPhone);
                cells["A13"].PutValue("Fax: " + invoice.BillToFax);
                //Ship To
                cells["I10"].PutValue(invoice.ShipToName);
                cells["I11"].PutValue(invoice.ShipToAddress);
                cells["I12"].PutValue("Tel: " + invoice.ShipToPhone);
                cells["I13"].PutValue("Fax: " + invoice.ShipToFax);
                //Provider
                cells["C15"].PutValue(invoice.ShipVia);
                cells["C16"].PutValue(invoice.ShipTerm);
                cells["I15"].PutValue(invoice.ShippingAccount + ": ");
                cells["K15"].PutValue(invoice.ShippingAccountValue);
                cells["K16"].PutValue(invoice.Tracking);
                
                //bottom
                cells["D27"].PutValue(manufacturing.Country);

                //Summary
                cells["I29"].PutValue(invoicePL.Sum(p => p.Quantity));
                cells["J29"].PutValue(invoicePL.Sum(p => p.CartonQuantity));
                cells["N29"].PutValue(invoicePL.Select(p => new { p.PackageNo, p.Weight }).Distinct().Sum(p=>p.Weight.Value));

                #region Insert dimension
                var lstDimension = new List<PackageDimension>();
                
                if (invoice.PackingType == 0)
                {//Đóng theo carton
                    foreach (var item in invoicePL)
                    {
                        var checkDimension = lstDimension.SingleOrDefault(p => p.Type == PackingTypeEnum.Type1 && p.Dimension == item.Dimension);
                        if (checkDimension == null)
                        {
                            var d = new PackageDimension();
                            d.Type = PackingTypeEnum.Type1;
                            d.Dimension = item.Dimension;
                            d.Quantity = item.CartonQuantity ?? 0;
                            lstDimension.Add(d);
                        }
                        else
                            checkDimension.Quantity += item.CartonQuantity ?? 0;
                    }
                }
                else// if (invoice.PackingType == 1)
                {//Theo pallet
                    var lstPalletDimension = invoicePL.Select(p => new { No = p.PackageNo, Mode = p.PackageUnit, Dimension = p.Dimension, Quantity = p.PalletQuantity }).Distinct().ToList();
                    foreach (var item in lstPalletDimension)
                    {
                        var checkDimension = lstDimension.SingleOrDefault(p => p.Type == item.Mode && p.Dimension == item.Dimension);
                        if (checkDimension == null)
                        {
                            var d = new PackageDimension();
                            d.Type = item.Mode;
                            d.Dimension = item.Dimension;
                            d.Quantity = item.Quantity ?? 0;
                            lstDimension.Add(d);
                        }
                        else
                            checkDimension.Quantity += item.Quantity ?? 0;
                    }
                }

                if (lstDimension.Count > 2)
                {
                    for (int i = 0; i < lstDimension.Count - 2; i++)
                    {
                        cells.InsertRow(25 + i);
                        cells.CopyRow(cells, 24, (25 + i));
                    }
                }
                for (int i = 0; i < lstDimension.Count(); i++)
                {
                    //Thay đổi tên đóng gói cho đẹp
                    lstDimension[i].Type = lstDimension[i].Quantity > 1 ? lstDimension[i].Type.Replace("Pallet", "pallets").Replace("Carton", "boxes")
                        : lstDimension[i].Type.Replace("Pallet", "pallet").Replace("Carton", "box");
                    cells["D" + (24 + i)].PutValue(String.Format("{0} {1} ({2})", lstDimension[i].Quantity, lstDimension[i].Type, lstDimension[i].Dimension));
                }
                #endregion

                rowIndex = 21;
                itemCount = invoicePL.Count;
                //Chèn thêm n dòng vào dòng được chỉ định
                if (itemCount > 1)
                {
                    for (int i = 0; i < itemCount - 1; i++)
                    {
                        cells.InsertRow(rowIndex + i);
                        cells.CopyRow(cells, rowIndex - 1, (rowIndex + i));
                    }
                }
                
                //Bắt đầu đổ dữ liệu
                for (var i = 0; i < invoicePL.Count; i++)
                {
                    var item = invoicePL[i];

                    //Cột STT
                    cells["A" + rowIndex].PutValue(i + 1);
                    //WO
                    cells["B" + rowIndex].PutValue(item.WO);
                    //Code
                    cells["C" + rowIndex].PutValue(item.ProductCode);
                    //Name
                    cells["D" + rowIndex].PutValue(item.ProductName);
                    //unit
                    cells["H" + rowIndex].PutValue(item.Unit);
                    //Quantity
                    cells["I" + rowIndex].PutValue(item.Quantity);
                    //carton quantity
                    cells["J" + rowIndex].PutValue(item.CartonQuantity);
                    //package quantity
                    cells["K" + rowIndex].PutValue(item.PalletQuantity);
                    //Unit
                    cells["L" + rowIndex].PutValue(item.PackageUnit);
                    //No
                    cells["M" + rowIndex].PutValue(item.PackageNo);
                    //WT
                    cells["N" + rowIndex].PutValue(item.Weight);

                    rowIndex++;
                }
                //merge cell
                if (invoice.PackingType != 0)
                {
                    var mergeIndex = 21;
                    var packageNo = invoicePL.Select(p => p.PackageNo).Distinct().ToList();
                    for (int i = 0; i < packageNo.Count(); i++)
                    {
                        var count = invoicePL.Count(p => p.PackageNo.ToString() == cells["M" + mergeIndex].Value.ToString());

                        cells.Merge(mergeIndex - 1, 10, count, 1);
                        cells.Merge(mergeIndex - 1, 11, count, 1);
                        cells.Merge(mergeIndex - 1, 12, count, 1);
                        cells.Merge(mergeIndex - 1, 13, count, 1);

                        mergeIndex += count;
                    }
                }
                #endregion

                try
                {
                    Common.SetAutoFitMergedCells(wsInvoice);
                    Common.SetAutoFitMergedCells(wsPackingList);
                    workbook.Save(fileName);

                    //Mở file Excel vừa lưu
                    if (exportType == 0) //Xuất excel
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                    else //In
                    {
                        Common.PrintExcelAuto(fileName, config.PrintCopies);
                    }
                }
                catch (Exception ex)
                {
                    Common.ShowErrorMess("ExportFile - " + ex.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("ExportFile - " + ex.Message);
                return;
            }
        }

        private void ExportList(List<Invoice> data, string fileName, int exportType)
        {
            try
            {
                //datacontext
                db = new UnigenDataContext();

                //Tạo một đối tượng workbook
                var stream = new MemoryStream(global::UnigenReport.Properties.Resources.InvoiceListReport);
                var workbook = new Workbook(stream);

                var cells = workbook.Worksheets[0].Cells;
                var rowIndex = 2;

                if (data.Count > 1)
                    cells.InsertRows(2, data.Count - 1);

                //Bắt đầu đổ dữ liệu
                for (var i = 0; i < data.Count; i++)
                {
                    var item = data[i];
                    var exPO = item.InvoiceDetails.OrderBy(p => p.WO).Select(p => p.PO).Distinct().ToList();
                    var exWO = item.InvoiceDetails.OrderBy(p => p.WO).Select(p => p.WO).Distinct().ToList();
                    var exCode = item.InvoiceDetails.OrderBy(p => p.WO).Select(p => p.ProductCode).Distinct().ToList();
                    var exName = item.InvoiceDetails.OrderBy(p => p.WO).Select(p => p.ProductName).Distinct().ToList();
                    //Cột STT
                    cells["A" + rowIndex].PutValue(i + 1);
                    cells["B" + rowIndex].PutValue(item.InvoiceNo);
                    cells["C" + rowIndex].PutValue(item.Date);
                    cells["D" + rowIndex].PutValue(String.Join("\n", exPO));
                    cells["E" + rowIndex].PutValue(String.Join("\n", exWO));
                    cells["F" + rowIndex].PutValue(item.Tracking);
                    cells["G" + rowIndex].PutValue(String.Join("\n", exCode));
                    cells["H" + rowIndex].PutValue(String.Join("\n", exName));
                    cells["I" + rowIndex].PutValue(item.InvoiceDetails.Sum(p=>p.Amount ?? 0));
                    cells["J" + rowIndex].PutValue(item.ShipTerm);                    

                    rowIndex++;
                }

                try
                {
                    workbook.Save(fileName);

                    //Mở file Excel vừa lưu
                    if (exportType == 0) //Xuất excel
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                    else //In
                    {
                        var config = new SystemConfig.UserConfig();
                        Common.PrintExcelAuto(fileName, config.PrintCopies);
                    }
                }
                catch (Exception ex)
                {
                    Common.ShowErrorMess("ExportList - " + ex.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("ExportList - " + ex.Message);
                return;
            }
        }

        private void ExportProducts(List<ExportInvoiceProduct> data, string fileName, int exportType)
        {
            try
            {
                //datacontext
                db = new UnigenDataContext();

                //Tạo một đối tượng workbook
                var stream = new MemoryStream(global::UnigenReport.Properties.Resources.InvoiceProductReport);
                var workbook = new Workbook(stream);

                var cells = workbook.Worksheets[0].Cells;
                var rowIndex = 2;

                if (data.Count > 1)
                    cells.InsertRows(2, data.Count - 1);

                //Bắt đầu đổ dữ liệu
                for (var i = 0; i < data.Count; i++)
                {
                    var item = data[i];

                    //Cột STT
                    cells["A" + rowIndex].PutValue(i + 1);
                    cells["B" + rowIndex].PutValue(item.ProductCode);
                    cells["C" + rowIndex].PutValue(item.ProductName);
                    cells["D" + rowIndex].PutValue(item.InvoiceNo);
                    cells["E" + rowIndex].PutValue(item.WO);
                    cells["F" + rowIndex].PutValue(item.Quantity);
                    cells["G" + rowIndex].PutValue(item.Price);
                    cells["H" + rowIndex].PutValue(item.Amount);

                    rowIndex++;
                }

                try
                {
                    workbook.Save(fileName);

                    //Mở file Excel vừa lưu
                    if (exportType == 0) //Xuất excel
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                    else //In
                    {
                        var config = new SystemConfig.UserConfig();
                        Common.PrintExcelAuto(fileName, config.PrintCopies);
                    }
                }
                catch (Exception ex)
                {
                    Common.ShowErrorMess("ExportProducts - " + ex.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("ExportProducts - " + ex.Message);
                return;
            }
        }

        #endregion
        
        #region Sự kiện

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                BindData();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void chkToDate_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            txtToDate.Enabled = chkToDate.Checked;
        }

        private void chkFromDate_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            txtFromDate.Enabled = chkFromDate.Checked;
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            Insert();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            UpdateInfo();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            var currentInvoice = sourceInvoice.Current as Invoice;
            if (currentInvoice == null) return;

            var dir = "Temp";
            if (!System.IO.File.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
            ExportFile(currentInvoice, dir + "\\" + currentInvoice.InvoiceNo + DateTime.Now.ToString("yyyyMMddHHmm"), 1);
        }

        private void btnExportList_Click(object sender, EventArgs e)
        {
            var source = GetData();
            if (source.Count == 0) return;

            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = String.Format("ListInvoice{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"))
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;
            ExportList(source, fileName, 0);
        }

        private void btnExportProduct_Click(object sender, EventArgs e)
        {
            var source = GetDataForExportProducts();
            if (source.Count == 0) return;

            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = String.Format("ListInvoiceByProduct{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"))
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;
            ExportProducts(source, fileName, 0);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var currentInvoice = sourceInvoice.Current as Invoice;
            if (currentInvoice == null) return;            

            //Xuat file
            var saveFileDialog = new SaveFileDialog
            {
                FileName = currentInvoice.InvoiceNo + ".xls"
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (saveFileDialog.FileName.Equals(String.Empty))
            {
                return;
            }

            var fileName = saveFileDialog.FileName;
            ExportFile(currentInvoice, fileName, 0);
        }

        private void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                if (sourceInvoice.Current == null)
                {
                    Common.ShowSelectionRequire();
                    return;
                }

                if (Common.ShowQuestion("Xác nhận invoice này?") != DialogResult.OK)
                    return;

                db = new UnigenDataContext();
                var inputItem = (sourceInvoice.Current as Invoice);
                if (inputItem.Approve ?? false)
                {
                    Common.ShowNoticeMess("Invoice này đã xác nhận!");
                    return;
                }
                //Approve
                var approveItem = db.Invoices.SingleOrDefault(p => p.InvoiceId == inputItem.InvoiceId);
                approveItem.Approve = true;

                //Thay đổi World order
                var detail = approveItem.InvoiceDetails;
                foreach (var item in detail)
                {
                    var wo = db.WorldOrders.SingleOrDefault(p => p.WO == item.WO);
                    if (wo != null)
                    {
                        wo.Shipped += item.Quantity;
                        wo.Remained -= item.Quantity;
                        if (wo.Remained == 0)
                            wo.Closed = true;
                    }
                }

                db.SubmitChanges();

                //Remove khỏi grid
                sourceInvoice.Remove(inputItem);

                //Thông báo
                Common.ShowSaveSuccess();
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Delete - " + ex.Message);
            }
        }

        private void btnCloseForm_Click(object sender, EventArgs e)
        {
            (this.Parent as Telerik.WinControls.UI.RadPageViewPage).Dispose();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void grvInvoice_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            UpdateInfo();
        }

        #endregion
    }

    public class PackageDimension
    {
        public string Type { get; set; }
        public string Dimension { get; set; }
        public int Quantity { get; set; }
    }

    public class ExportInvoiceProduct
    { 
        public string ProductCode {get; set;}
        public string ProductName {get; set;}
        public string InvoiceNo {get; set;}
        public string WO {get; set;}
        public int Quantity {get; set;}
        public decimal Price {get; set;}
        public decimal Amount { get; set; }
    }
}
